/**
 * Binder.java
 * 12 mai 2010 20:45:01
 * Copyright Julien 2010
 */
package fr.jbrunet.win.ndriveconnector;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import fr.jbrunet.logger.JLog;
import fr.jbrunet.win.ndriveconnector.config.Config;

/**
 * @author Julien
 *
 */
public class DriveBinder {
	
	private static final Logger log = JLog.getLogger(DriveBinder.class);	
	private static DriveBinder instance__ = null;
	
	
	/**
	 * @throws Exception 
	 * 
	 */
	public DriveBinder() throws Exception {
		Config.getInstance();
	}

	/**
	 * @return the instance__
	 * @throws Exception 
	 */
	public static DriveBinder getInstance() throws Exception {
		if (instance__==null) {
			instance__ = new DriveBinder();
		}
		return instance__;
	}
	
	/**
	 * Launch all necessary command to connect all drive
	 * @throws Exception 
	 */
	public void connectDrives() throws Exception {		
		for(int i = 0; i < Config.getInstance().getCommands().size(); i++) {
			executeCommand(Config.getInstance().getCommands().get(i));
		}
	}
	
	/**
	 * Execute system command
	 * @param cmd
	 * @throws Exception 
	 * @throws Exception 
	 */
	private static void executeCommand(String cmd) throws Exception  {
		if (cmd == null || cmd.length() == 0) {
			log.error ("cmd cannot be empty");
		} else {
			Runtime r = Runtime.getRuntime();
			log.info ("# "+StringUtils.replace(cmd,Config.getInstance().getUser().getPassword(), "*********"));
			try {	
				Process p;
				String outputLine = "";

				p = r.exec(cmd);
				p.waitFor();

				BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
				while ((outputLine = input.readLine()) != null) {
					//remove password from the log
					outputLine = StringUtils.replace(outputLine, Config.getInstance().getUser().getPassword(), "*********");
					log.info("# " + outputLine);
				}
				BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
				while ((outputLine = error.readLine()) != null) {
					outputLine = StringUtils.replace(outputLine, Config.getInstance().getUser().getPassword(), "*********");
					log.error("# " + outputLine);
				}
				input.close();				
			} catch (IOException e) {
				log.error("Erreur lors de l'execution de la commande '" + cmd + "'", e);
			} catch (InterruptedException e) {
				log.error("Erreur lors de l'execution de la commande '" + cmd + "'", e);
			}
		}
	}
}	
